package com.android.server.actionHandler;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.commons.lang.StringUtils;

import com.android.client.entity.ConfEntity;
import com.android.client.event.AbstractEvent;
import com.android.client.event.ConfEditorStateSwitchEvent;
import com.android.server.jdo.ConfJdo;
import com.google.appengine.api.datastore.Text;
import com.google.gwt.event.shared.EventHandler;

public class ConfSaveHandler extends ActionHandler {

	@Override
	public String execute(AbstractEvent<? extends EventHandler> event) {
		PersistenceManager pm = pmf.getPersistenceManager();
		ConfEditorStateSwitchEvent cEvent = (ConfEditorStateSwitchEvent) event;
		try {
			ConfEntity entity = cEvent.getConfJdo();
			switch (cEvent.getType()) {
			case ConfEditorStateSwitchEvent.SAVE_CONF:
				String confStr = entity.getConf();
				String version = StringUtils.substringBetween(confStr, "<version>",
						"</version>");
				if (version == null) {
					return "false";
				}

				ConfJdo jdo = new ConfJdo(version, entity.getGroup(), new Text(
						confStr));
				pm.makePersistent(jdo);
				pm.flush();
				return "true";
			case ConfEditorStateSwitchEvent.LOAD_CONF:
				Query query = pm.newQuery(ConfJdo.class);
				query.setFilter("group == " + entity.getGroup());
				List confList = (List) query.execute();
				Iterator<ConfJdo> confItr = confList.iterator();
				if(confItr.hasNext()){
					ConfJdo cJdo = confItr.next();
					Text conf = cJdo.getConf();
					return conf != null ? conf.getValue() : "no conf xml";
				}else{
					return "no conf xml";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			if(cEvent.getType() == ConfEditorStateSwitchEvent.SAVE_CONF){
				return "false";
			}
		} finally {
			pm.close();
		}
		return null;
	}

}
